import { G } from '../common'
cc.Class({
    extends: cc.Component,

    properties: {
        Mousemove: cc.Node, //飞船
        prefabQiu: cc.Prefab,
        Airship: cc.Node,
        Height: 1600,
        Width: 800,
        Star: cc.Node,
        num: cc.Label,
        Line: cc.Node,
        startTime: 0,
        juicePrefab: cc.Prefab, //果汁
        scoreAudio: cc.AudioClip, // 得分音效资源
        ClickAudio: cc.AudioClip,
        bgAudio: cc.AudioClip,
        CelebrateAudio: cc.AudioClip,
        Score: cc.Label,
        Result: cc.Node,
        Celebrate: cc.Node
    },

    onLoad() {
        // 开启物理系统
        cc.director.getPhysicsManager().enabled = true;
        // 先关闭重力
        cc.director.getPhysicsManager().gravity = cc.v2(0, 0);
        // 绑定鼠标移动事件
        this.node.on(cc.Node.EventType.TOUCH_START, this.mouseFunStart, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.mouseFun, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.mouseFunEnd, this);
        this.SetPosition();
        this.DrawBall(0); //初始化小球
        cc.audioEngine.playEffect(this.bgAudio, true); //背景音乐
        // cc.resources.preload('img/planet_list/fruit', cc.SpriteAtlas);
        cc.resources.preload('img/planet_list/planet', cc.SpriteAtlas);
        cc.resources.preload('img/planet_list/juice', cc.SpriteAtlas);

        // console.log("Line")
        // console.log(this.Line.y)


    },

    SetPosition() {
        this.Height = cc.view.getVisibleSize().height;
        this.Width = cc.view.getVisibleSize().width;
        this.Line.y = this.Height / 3 - 100;
        this.Mousemove.y = this.Height / 3;
    },

    //区域控制
    scene(pos) {
        //转换为节点(局部)空间坐标系
        pos = this.node.convertToNodeSpaceAR(pos); //将一个点转换到节点 (局部) 空间坐标系，这个坐标系以锚点为原点。

        // console.log(pos);

        //给要移动的物体赋值
        this.Mousemove.position = pos;
        //this.Mousemove.y = this.Height / 3;
        if (this.Mousemove.x < -this.Width / 2 + 90) {
            this.Mousemove.x = -this.Width / 2 + 90;
        }
        if (this.Mousemove.x > this.Width / 2 - 90) {
            this.Mousemove.x = this.Width / 2 - 90;
        }
    },
    buttonClick() {
        // 设置重力
        cc.director.getPhysicsManager().gravity = cc.v2(0, -2000);
        this.initboard();
    },
    getRandomBall(max) {
        const len = G.randomBall.length;
        const r = parseInt(Math.random() * len, 10);
        if (G.randomBall[r] <= max) {
            const index = Object.keys(G.BallArr).findIndex(x => x == G.randomBall[r])
            return index;
        } else {
            return this.getRandomBall(max);
        }
    },
    // 合并时的动画效果
    createFruitJuice(other, n, m = 10) {
        // console.log("合并时的动画效果");
        // console.log(other);
        var thenum = Math.log(n) / Math.log(2);
        //音效
        cc.audioEngine.playEffect(this.scoreAudio, false);
        let width = G.BallArr[n] * m;
        // 展示动画
        let juice = cc.instantiate(this.juicePrefab);
        other.addChild(juice);
        const instance = juice.getComponent('Juice');
        //果汁图片
        cc.resources.load("img/planet_list/juice", cc.SpriteAtlas, function(err, atlas) {

            var particles = atlas.getSpriteFrame('juice_l_' + thenum);
            var circle = atlas.getSpriteFrame('juice_o_' + thenum);
            var slash = atlas.getSpriteFrame('juice_q_' + thenum);
            var config = {
                particle: particles,
                circle: circle,
                slash: slash
            }
            instance.init(config);
            instance.showJuice(0, width);
        });

    },
    //相同水果碰撞 n:1024
    SameFruitContact(self, other, n, iswaterM) {

        if (iswaterM) return;
        const { x, y } = other.node;
        self.node.getChildByName('num').getComponent(cc.Label).string = 0;
        other.node.getChildByName('num').getComponent(cc.Label).string = 0;


        self.node.removeFromParent(true);
        other.node.removeFromParent(true);

        var item = cc.instantiate(this.prefabQiu); //实例化一个预制体
        item.getComponent('coliderlisten').init({
            num: n,
            is_anim: true
        });
        item.on('sameContact', this.SameFruitContact.bind(this));
        item.setPosition(cc.v2(x, y));
        this.createFruitJuice(item, n); //合成动画


        this.Mousemove.addChild(item);

        //得分
        this.Score.string = parseInt(this.Score.string) + n / 4;

        //判断大西瓜
        if (n == 2048) {
            //console.log("庆祝");
            //this.Celebrate.active = true;
            //放烟花
            this.createFruitJuice(this.Celebrate, 1024, 100);
            this.createFruitJuice(this.Celebrate, 128, 100);
            this.createFruitJuice(this.Celebrate, 32, 100);
            // //音效
            cc.audioEngine.playEffect(this.CelebrateAudio, false);
            setTimeout(() => {
                //this.Celebrate.active = false;
            }, 2000);
        }

    },
    clacItemHeight(item) {
        //记录高度
        const r = item.height * item.scale / 2; //半径
        let qiu_y;
        //console.log("小球",item.y);
        if (item.y < 0) {
            qiu_y = this.Mousemove.y - Math.abs(item.y);
        }

        //console.log("x球：",qiu_y)
        //console.log("MouseMoce",this.Mousemove.y)
        //游戏结束
        //G.maxHeight = G.maxHeight > this.Line.y ? this.GameOver() : qiu_y + r;
    },
    GameOver() {
        setTimeout(function() {
            this.Result.active = true;
        }, 600)
    },
    TanResult() {
        cc.director.loadScene("rank");
    },
    initboard() {

        var item = cc.instantiate(this.prefabQiu); //实例化一个预制体
        item.getComponent('coliderlisten').init({
            num: this.num.string,
        })
        item.on('sameContact', this.SameFruitContact.bind(this));
        this.Mousemove.addChild(item);

        this.Mousemove.x = 0; //固定飞船在中间
        this.Star.active = false; //隐藏假球

        //音效
        cc.audioEngine.playEffect(this.ClickAudio, false);

        const max = Object.keys(G.BallArr).findIndex(x => x == G.maxNum)

        let aIndex;
        aIndex = G.maxNum > 32 ? 32 : G.maxNum
        const roundNum = this.getRandomBall(aIndex);

        this.DrawBall(roundNum);
    },
    DrawBall(n) {
        // console.log(n);
        if (n > 10) return;
        const arr = Object.keys(G.BallArr);
        const num = arr[n];
        //小球赋值
        this.num.string = num;
        //小球大小
        //this.Star.setScale(G.BallArr[num]);
        cc.tween(this.Star)
            .to(0.3, { scale: G.BallArr[num] * 0.5 })
            .to(0.6, { scale: G.BallArr[num] })
            .start()
            //小球图片
        var thenum = Math.log(num) / Math.log(2);
        cc.resources.load("img/planet_list/fruit", cc.SpriteAtlas, (err, atlas) => {
            this.Star.getComponent(cc.Sprite).spriteFrame = atlas.getSpriteFrame('fruit_' + thenum);
        });
        //打开小球
        // this.Star.active = true;

        setTimeout(() => {
            //打开小球
            this.Star.active = true;
        }, 600)
    },



    //鼠标进入
    mouseFunStart(event) {
        const pos = new cc.Vec2(event.getLocationX(), event.getLocationY());
        this.scene(pos);
    },
    //鼠标移动
    mouseFun(event) {
        const pos = new cc.Vec2(event.getLocationX(), event.getLocationY());
        this.scene(pos);
    },
    //鼠标离开
    mouseFunEnd(event) {
        // let timeNow = +new Data();
        // if (timeNow - this.startTime >= 500) {
        //     this.buttonClick();
        //     this.startTime = timeNow;
        // }
        this.buttonClick();
    },



    //回主页
    OnclickReturn() {
        cc.director.loadScene("home");
    },

    //重新开始
    OnclickReStart() {
        cc.director.loadScene("home");
    }

});